package cn.hh.wechatkit.util;

import cn.hh.wechatkit.pojo.message.Wx_EventTypeEnum;
import cn.hh.wechatkit.pojo.message.Wx_IMsg;
import cn.hh.wechatkit.pojo.message.Wx_MsgTypeEnum;
import cn.hh.wechatkit.pojo.message.imp.commumication.*;
import cn.hh.wechatkit.pojo.message.imp.event.ticket.Wx_TicketConsumeEventMsg;
import cn.hh.wechatkit.pojo.message.imp.event.ticket.Wx_TicketGetEventMsg;
import cn.hhchat.kit.xml.XmlUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.security.InvalidParameterException;
import java.util.Map;

import static cn.hhchat.kit.xml.XmlUtil.xmlToMap;

/**
 * Created this one by HMH on 2017/7/11.
 */
@Slf4j
public class WxMessageUtil {

    public static Wx_IMsg decodeMeg(HttpServletRequest request) {
        Map<String, String> map = XmlUtil.xmlToMap(request);
        return genFromMap(map);
    }

    /**
     * 一定要保证msgType不为空
     */
    public static Wx_IMsg genFromMap(Map<String, String> map) {
        String type = map.getOrDefault("MsgType", "");
        Wx_MsgTypeEnum msgTypeEnum = Wx_MsgTypeEnum.fromString(type, "类型");
        switch (msgTypeEnum) {
            case text:
                return new Wx_TextMsg(map);
            case link:
                return new Wx_LinkMsg(map);
            case image:
                return new Wx_PicMsg(map);
            case video:
                return new Wx_VideoMsg(map);
            case news:
                return new Wx_ArticleMsg(map);
            case voice:
                return new Wx_VoiceMsg(map);
            case event:{
                Wx_EventTypeEnum eventTypeEnum = Wx_EventTypeEnum.fromString(map.get("Event"), "事件类型");
                switch (eventTypeEnum) {
                    case user_get_card:
                        return new Wx_TicketGetEventMsg(map);
                    case user_consume_card:
                        return new Wx_TicketConsumeEventMsg(map);
                }
            }
        }
        log.error(" 🌧 参数错误，无法转换" + JSON.toJSONString(map));
        throw new InvalidParameterException("参数错误，无法转换");
    }


}
